package cn.akwangl.future;

import java.util.concurrent.*;

/**
 * 执行任务时,发生异常.
 * 结论:
 * 1. 不管线程池中执行的任务抛出什么异常都归结于{@link ExecutionException}.
 * 2. 如果任务率先抛出异常时,只有调用者{@link Future#get()}方法才会发生异常.
 *
 * @author 阿坤同学
 * @date 2022/12/20 16:40
 */
public class GetException {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        // 直接抛出异常
        Callable<Integer> task = () -> {
            System.out.println("Callable 执行代码");
            throw new IllegalArgumentException("Callable 异常");
        };

        Future<Integer> future = executorService.submit(task);

        try {
            Thread.sleep(5000L);

            Integer integer = future.get();
            System.out.println(integer);
        } catch (InterruptedException e) {
            System.out.println("InterruptedException 异常");
            e.printStackTrace();
        } catch (ExecutionException e) {
            System.out.println("ExecutionException 异常");
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}
